package cn.com.nr.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.stereotype.Controller;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasMineExportEntity;
import cn.com.gas.service.GasMineExportService;
import cn.com.nr.entity.NrDiggingsEndangerEntity;
import cn.com.nr.entity.NrRecordsEntity;
import cn.com.nr.service.NrDiggingsEndangerService;
import cn.com.nr.service.NrRecordsService;
import cn.com.nr.vo.excel.NrRecordsExcel;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 混凝土车辆维护
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2025-02-08 16:34:40
 */
@Controller
@RequestMapping("/nr/diggingsSelect")
@Log4j
public class NrDiggingsSelectController {
	@Autowired
	private NrRecordsService nrRecordsService;
	@Autowired
	private HttpSessionService httpSessionService;
	@Autowired
	private NrDiggingsEndangerService nrDiggingsEndangerService;
	@Autowired
	private GasMineExportService gasMineExportService;
	
	@Autowired
	private DeptService deptService;
	
	@Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据")
	@PostMapping("/list")
	@ResponseBody
	public DataResult list(@RequestBody NrRecordsEntity nrRecords) throws ParseException {

		String currentDeptId = httpSessionService.getCurrentDeptId();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String deptId = nrRecords.getDeptId();
		String stationName = nrRecords.getStationName();

		LambdaQueryWrapper<NrDiggingsEndangerEntity> queryWrapperStationinfo = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(deptId)) {
			queryWrapperStationinfo.eq(NrDiggingsEndangerEntity::getTaxorgcode, deptId);
		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapperStationinfo.eq(NrDiggingsEndangerEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapperStationinfo.like(NrDiggingsEndangerEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
			}
		}

		if (TsBqUtils.isNotNull(stationName)) {
			queryWrapperStationinfo.like(NrDiggingsEndangerEntity::getName, stationName);
		}
		
		queryWrapperStationinfo.eq(NrDiggingsEndangerEntity::getIndustry, "铁矿选矿");
		
		List<NrDiggingsEndangerEntity> listNr = nrDiggingsEndangerService.list(queryWrapperStationinfo);
		
		List<String> nrIdList = new ArrayList<>();
		
		for (NrDiggingsEndangerEntity nr : listNr) {
			String id = nr.getId();
			nrIdList.add(id);
		}
		
		if (TsBqUtils.isNotNull(nrIdList)) {
			Page page = new Page(nrRecords.getPage(), nrRecords.getLimit());
			LambdaQueryWrapper<NrRecordsEntity> queryWrapper = Wrappers.lambdaQuery();
			// 查询条件示例
			
			if (!StringUtils.isEmpty(nrRecords.getCreateTimeStart())) {
				queryWrapper.ge(NrRecordsEntity::getTime,
						sdf.parse(nrRecords.getCreateTimeStart() + " 00:00:00"));
			}
			if (!StringUtils.isEmpty(nrRecords.getCreateTimeEnd())) {
				queryWrapper.le(NrRecordsEntity::getTime,
						sdf.parse(nrRecords.getCreateTimeEnd() + " 23:59:59"));
			}

			// queryWrapper.eq(NrRecordsEntity::getMessageRulename, "升降机");
			
			queryWrapper.in(NrRecordsEntity::getNrEndanger, nrIdList);
			
			queryWrapper.orderByDesc(NrRecordsEntity::getTime);

			IPage<NrRecordsEntity> iPage = nrRecordsService.page(page, queryWrapper);
			List<NrRecordsEntity> records = iPage.getRecords();
			for (NrRecordsEntity nrRecordsEntity : records) {
				String nrEndanger = nrRecordsEntity.getNrEndanger();
				NrDiggingsEndangerEntity diggingsEndangerEntity = nrDiggingsEndangerService.getById(nrEndanger);
				if(TsBqUtils.isNotNull(diggingsEndangerEntity)){
					
					String diggingsEndangerName = diggingsEndangerEntity.getName();
					nrRecordsEntity.setStation(diggingsEndangerName);
					
					String taxorgcode = diggingsEndangerEntity.getTaxorgcode();
					SysDept sysDept = deptService.getById(taxorgcode);
					
					if(TsBqUtils.isNotNull(sysDept)){
						String name = sysDept.getName();
						nrRecordsEntity.setDeptName(name);
					}
					String taxpayerCode = diggingsEndangerEntity.getTaxpayerCode();
					nrRecordsEntity.setTaxpayerCode(taxpayerCode);
					nrRecordsEntity.setIndustry(diggingsEndangerEntity.getIndustry());

				}
			}
			return DataResult.success(iPage);
		}else{
			return DataResult.fail("暂无分析业务数据");
		}
	}
	
	
	@PostMapping("/exportData")
	@ResponseBody
	public DataResult exportData(@RequestBody NrRecordsEntity nrRecords)
			throws java.io.IOException, ParseException {
		
		if (TsBqUtils.isNull(nrRecords.getCreateTimeStart())) {
			return DataResult.success("start-MessageDisappear不能为空！");
		}
		
		if (TsBqUtils.isNull(nrRecords.getCreateTimeEnd())) {
			return DataResult.success("end-MessageDisappear不能为空！");
		}
		
		String currentDeptId = httpSessionService.getCurrentDeptId();
		String currentUserId = httpSessionService.getCurrentUserId();

		// 插入gas_mine_export表
		GasMineExportEntity mineExportEntity = new GasMineExportEntity();
		String uuid = TsBqUtils.getUUID();
		mineExportEntity.setId(uuid);
		mineExportEntity.setModule("铁矿选矿-车流记录");

		mineExportEntity.setDeleted(Constants.DATA_NOT_DELETED);
		mineExportEntity.setCreateTime(new Date());
		mineExportEntity.setCreateId(currentUserId);
		mineExportEntity.setCreateTaxorgcode(currentDeptId);

		gasMineExportService.save(mineExportEntity);
		
		new Thread(() -> {
			try {
				log.info("睡眠前");
				Thread.sleep(20000);// 休眠时间设置为10000毫秒（10秒）
				log.info("睡眠后");
				asynExportData(nrRecords, uuid, currentDeptId);

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}).start();

		return DataResult.success("稍后请在【我的导出】进行下载导出内容！");
		
	}
	
	
	
	private void asynExportData(NrRecordsEntity nrRecords, String uuid, String currentDeptId)
			throws ParseException {

		GasMineExportEntity gasMineExportEntity = gasMineExportService.getById(uuid);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String deptId = nrRecords.getDeptId();
		String stationName = nrRecords.getStationName();

		LambdaQueryWrapper<NrDiggingsEndangerEntity> queryWrapperStationinfo = Wrappers.lambdaQuery();
		if (TsBqUtils.isNotNull(deptId)) {
			queryWrapperStationinfo.eq(NrDiggingsEndangerEntity::getTaxorgcode, deptId);
		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapperStationinfo.eq(NrDiggingsEndangerEntity::getTaxorgcode, currentDeptId);

			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapperStationinfo.like(NrDiggingsEndangerEntity::getTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
			}
		}

		if (TsBqUtils.isNotNull(stationName)) {
			queryWrapperStationinfo.like(NrDiggingsEndangerEntity::getName, stationName);
		}
		
		queryWrapperStationinfo.eq(NrDiggingsEndangerEntity::getIndustry, "铁矿选矿");
		
		List<NrDiggingsEndangerEntity> listNr = nrDiggingsEndangerService.list(queryWrapperStationinfo);
		
		List<String> nrIdList = new ArrayList<>();
		
		for (NrDiggingsEndangerEntity nr : listNr) {
			String id = nr.getId();
			nrIdList.add(id);
		}
		
		if (TsBqUtils.isNotNull(nrIdList)) {
			LambdaQueryWrapper<NrRecordsEntity> queryWrapper = Wrappers.lambdaQuery();
			// 查询条件示例
			if (!StringUtils.isEmpty(nrRecords.getCreateTimeStart())) {
				queryWrapper.ge(NrRecordsEntity::getTime,
						sdf.parse(nrRecords.getCreateTimeStart() + " 00:00:00"));
			}
			if (!StringUtils.isEmpty(nrRecords.getCreateTimeEnd())) {
				queryWrapper.le(NrRecordsEntity::getTime,
						sdf.parse(nrRecords.getCreateTimeEnd() + " 23:59:59"));
			}

			queryWrapper.in(NrRecordsEntity::getNrEndanger, nrIdList);
			
			queryWrapper.orderByDesc(NrRecordsEntity::getTime);

			List<NrRecordsEntity> records = nrRecordsService.list(queryWrapper);
			for (NrRecordsEntity nrRecordsEntity : records) {
				String nrEndanger = nrRecordsEntity.getNrEndanger();
				NrDiggingsEndangerEntity diggingsEndangerEntity = nrDiggingsEndangerService.getById(nrEndanger);
				if(TsBqUtils.isNotNull(diggingsEndangerEntity)){
					
					String diggingsEndangerName = diggingsEndangerEntity.getName();
					nrRecordsEntity.setStation(diggingsEndangerName);
					
					String taxorgcode = diggingsEndangerEntity.getTaxorgcode();
					SysDept sysDept = deptService.getById(taxorgcode);
					
					if(TsBqUtils.isNotNull(sysDept)){
						String name = sysDept.getName();
						nrRecordsEntity.setDeptName(name);
					}
					String taxpayerCode = diggingsEndangerEntity.getTaxpayerCode();
					nrRecordsEntity.setTaxpayerCode(taxpayerCode);
					nrRecordsEntity.setIndustry(diggingsEndangerEntity.getIndustry());
				}
			}
			
			
			if (records.size() > 0) {

				List<NrRecordsExcel> nrRecordsExcelList = new ArrayList<>();

				for (NrRecordsEntity nrRecordsEntity : records) {

					NrRecordsExcel nrRecordsExcel = NrRecordsExcel.builder()
							.id(nrRecordsEntity.getId())
							.station(nrRecordsEntity.getStation())
							.taxpayerCode(nrRecordsEntity.getTaxpayerCode())
							.deptName(nrRecordsEntity.getDeptName())
							.time(nrRecordsEntity.getTime())
							.messageCamid(nrRecordsEntity.getMessageCamid())
							.messageRulename("矿车")
							.calculate(nrRecordsEntity.getCalculate())
							.industry(nrRecordsEntity.getIndustry())
							.image(nrRecordsEntity.getImage())
							.build();

					nrRecordsExcelList.add(nrRecordsExcel);

				}

				String fileName = TsBqUtils.getUUID() + ".xlsx";

				String excelPath = filePath + fileName;
				OutputStream out = null;

				try {
					out = new FileOutputStream(excelPath);
					ExcelWriter writer = EasyExcelFactory.getWriter(out);

					Sheet sheet1 = new Sheet(1, 0, NrRecordsExcel.class);
					sheet1.setSheetName("数据");
					writer.write(nrRecordsExcelList, sheet1);
					// 将上下文中的最终 outputStream 写入到指定文件中
					writer.finish();
					File excelFile = new File(excelPath);
					List<Object> excelFileInfo = new ArrayList<>();
					excelFileInfo.add(fileName);
					excelFileInfo.add(excelFile.length());
					excelFileInfo.add(fileUrl + "/" + fileName);

					// return DataResult.success(excelFileInfo);

					gasMineExportEntity.setFileName(fileName);
					gasMineExportEntity.setUrl(fileUrl + "/" + fileName);
					gasMineExportEntity.setSize(excelFile.length() + "");
					gasMineExportEntity.setState("2");
					gasMineExportEntity.setDescription("导出成功！");
					gasMineExportEntity.setUpdateTime(new Date());
					gasMineExportService.updateById(gasMineExportEntity);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					gasMineExportEntity.setState("2");
					gasMineExportEntity.setDescription("xlsx生成失败：" + e.toString());
					gasMineExportEntity.setUpdateTime(new Date());
					gasMineExportService.updateById(gasMineExportEntity);
				} finally {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
						gasMineExportEntity.setState("2");
						gasMineExportEntity.setDescription("xlsx生成失败：" + e.toString());
						gasMineExportEntity.setUpdateTime(new Date());
						gasMineExportService.updateById(gasMineExportEntity);
					}

				}

			} else {
				gasMineExportEntity.setState("2");
				gasMineExportEntity.setDescription("暂无分析业务数据！");
				gasMineExportEntity.setUpdateTime(new Date());
				gasMineExportService.updateById(gasMineExportEntity);
			}
			
		}else{
			gasMineExportEntity.setState("2");
			gasMineExportEntity.setDescription("暂无企业数据！");
			gasMineExportEntity.setUpdateTime(new Date());
			gasMineExportService.updateById(gasMineExportEntity);
		}

	}
	
	
}
